import collections


class Solution(object):
    def minReorder(self, n, connections):
        d1 = collections.defaultdict(set)
        d2 = collections.defaultdict(set)
        p = [0] * n
        for u, v in connections:
            d1[u].add(v)
            d2[v].add(u)
        self.ans = 0
        p[0] = 1

        def dfs(node):
            for v in d1[node]:
                if not p[v]:
                    p[v] = 1
                    self.ans += 1
                    dfs(v)
            for v in d2[node]:
                if not p[v]:
                    p[v] = 1
                    dfs(v)

        dfs(0)
        return self.ans